<template>
  <div>
    <a-modal
      v-model="visible"
      :title="SKUTitle"
      width="60%"
      @ok="handleOk"
      @cancel="handleClose"
    >
      <template slot="footer" class="modelBtn">
        <a-button @click="handleClose" style="margin-right: 15px"
          >取消</a-button
        >
        <a-button type="primary" @click="handleOk" :loading="loading"
          >确认</a-button
        >
      </template>
      <!-- 产品基本信息 -->
      <div class="product-info">
        <h3>产品基本信息</h3>
        <a-form-model
          ref="infoRuleForm"
          :model="skuTableSelect"
          :rules="basicRules"
          class="product-input"
        >
          <a-form-model-item label="中文名称：" prop="chineseName">
            <a-input
              :maxLength="128"
              size="small"
              :disabled="isSKUEdit"
              placeholder="商品中文名称"
              v-model="skuTableSelect.chineseName"
            />
          </a-form-model-item>
          <a-form-model-item label="英文名称：" prop="englishName">
            <a-input
              :maxLength="128"
              size="small"
              :disabled="isSKUEdit"
              placeholder="商品英文名称"
              v-model="skuTableSelect.englishName"
            />
          </a-form-model-item>
          <a-form-model-item label="产品品牌：">
            <a-input
              :maxLength="128"
              placeholder="产品品牌"
              size="small"
              v-model="skuTableSelect.productBrand"
            />
          </a-form-model-item>
          <a-form-model-item label="产品型号：">
            <a-input
              :maxLength="128"
              size="small"
              placeholder="产品型号"
              v-model="skuTableSelect.productType"
            />
          </a-form-model-item>
          <a-form-model-item label="生产地址：">
            <a-input
              :maxLength="128"
              size="small"
              placeholder="生产地址"
              v-model="skuTableSelect.productionAddress"
            />
          </a-form-model-item>
          <a-form-model-item label="SKU：" prop="sku">
            <a-input
              :maxLength="128"
              :disabled="isSKUEdit"
              id="sku"
              placeholder="SKU"
              size="small"
              v-model="skuTableSelect.sku"
            />
          </a-form-model-item>
          <a-form-model-item label="关联SKU：" prop="relevancySku">
            <a-input
              :maxLength="128"
              placeholder="关联SKU"
              size="small"
              v-model="skuTableSelect.relevancySku"
            />
          </a-form-model-item>
          <a-form-model-item
            label="长*宽*高(最大274): "
            :required="true"
            class="lwh"
          >
            <a-form-model-item prop="long" :validateStatus="status">
              <a-input-number
                size="small"
                @blur="changeLwh"
                @change="changeLong(1)"
                :min="0.01"
                style="width: 100%"
                placeholder="长（cm）"
                :precision="2"
                :disabled="isSKUEdit"
                class="ct-long"
                v-model="skuTableSelect.long"
              />
              *
            </a-form-model-item>
            <a-form-model-item prop="width" :validateStatus="status">
              <a-input-number
                style="width: 100%"
                v-model="skuTableSelect.width"
                size="small"
                @blur="changeLwh"
                @change="changeLong(2)"
                :min="0.01"
                :precision="2"
                placeholder="宽（cm）"
                :disabled="isSKUEdit"
              />
              *
            </a-form-model-item>
            <a-form-model-item
              class="height"
              prop="height"
              :validateStatus="status"
            >
              <a-input-number
                style="width: 100%"
                :disabled="isSKUEdit"
                size="small"
                :min="0.01"
                :precision="2"
                @blur="changeLwh"
                @change="changeLong(3)"
                placeholder="高（cm）"
                v-model="skuTableSelect.height"
              />
            </a-form-model-item>
            <!-- <a-form-model-item prop="unitSystem" class="height">
              <a-select
                style="margin-left: 15px"
                show-search
                size="small"
                :disabled="isSKUEdit"
                @change="changeUnit"
                option-filter-prop="children"
                v-model="skuTableSelect.unitSystem"
                allowClear
                placeholder="单位"
              >
                <a-select-option
                  :value="item.value"
                  v-for="item in unitOption"
                  :key="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item> -->
            <a-form-model-item style="margin-left: 15px">
              <div
                v-if="
                  skuTableSelect.long &&
                  skuTableSelect.width &&
                  skuTableSelect.height
                "
              >
                {{
                  chanUnit.longUnit +
                  "：" +
                  chanUnit.long +
                  "*" +
                  chanUnit.width +
                  "*" +
                  chanUnit.height
                }}
              </div>
            </a-form-model-item>
          </a-form-model-item>
          <a-form-model-item
            label="长*宽*高(核重后): "
            class="nuclear"
            v-if="
              skuTableSelect.nuclearLength &&
              skuTableSelect.nuclearWidth &&
              skuTableSelect.nuclearHeight
            "
          >
            <div style="margin-left: 10px">
              {{
                " " +
                skuTableSelect.nuclearLength +
                "*" +
                skuTableSelect.nuclearWidth +
                "*" +
                skuTableSelect.nuclearHeight +
                "cm"
              }}
            </div>
          </a-form-model-item>
          <a-form-model-item label="重量：" prop="weight" style="width: 70%">
            <a-input-number
              size="small"
              style="width: 25%"
              :min="0.01"
              @change="changeweight"
              :precision="2"
              :disabled="isSKUEdit"
              placeholder="重量（g）"
              v-model="skuTableSelect.weight"
            />
            <!-- <a-select
              style="margin-left: 5px; width: 20%"
              show-search
              size="small"
              :disabled="isSKUEdit"
              @change="changeWeightUnit"
              option-filter-prop="children"
              v-model="skuTableSelect.unitWeight"
              allowClear
              placeholder="单位"
            >
              <a-select-option
                :value="item.value"
                v-for="item in weightOption"
                :key="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select> -->
            &nbsp;
            <span v-if="skuTableSelect.weight">
              {{ chanUnit.weightUnit + " : " + chanUnit.weight }}
            </span>
          </a-form-model-item>
          <a-form-model-item
            label="重量(核重后): "
            class="nuclear"
            v-if="skuTableSelect.nuclearWeight"
          >
            <div>
              {{ " " + skuTableSelect.nuclearWeight + "g" }}
            </div>
          </a-form-model-item>
          <a-form-model-item
            label="产品分类："
            prop="platformClassify"
            class="plat-class"
          >
            <a-cascader
              change-on-select
              style="width: 70%"
              size="small"
              :options="platformOptions"
              :show-search="{ filter }"
              placeholder="请选择分类"
              :disabled="isSKUEdit"
              @change="onChangeplatformOptions"
              v-model="skuTableSelect.platformClassify"
            />
          </a-form-model-item>
          <a-form-model-item label="包装类型：" prop="packingTypeName">
            <a-select
              size="small"
              v-model="skuTableSelect.packingType"
              :disabled="isSKUEdit"
              style="width: 70%"
              placeholder="请选择包装类型"
              @change="changePackingType"
            >
              <a-select-option
                v-for="item in tagsType"
                :value="item.key"
                :key="item.key"
              >
                {{ item.title }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="是否含有液体：" prop="isLiquid">
            <a-radio-group
              name="radioGroup"
              :default-value="1"
              :disabled="isSKUEdit"
              v-model="skuTableSelect.isLiquid"
            >
              <a-radio :value="1"> 否 </a-radio>
              <a-radio :value="0"> 是 </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <!-- label="自有分类：" -->
          <!-- <a-form-model-item prop="selfClassifyName" class="my-class">
             <a-cascader
              change-on-select
              size="small"
              style="width: 70%"
              :options="freedomOptions"
              :show-search="{ filter }"
              placeholder="请选择分类"
              @change="onChangefreedomOptions"
              v-model="skuTableSelect.selfClassify"
            />
          </a-form-model-item> -->
          <a-form-model-item label="是否含有电池：" prop="isBattery">
            <a-radio-group
              name="radioGroup"
              :default-value="1"
              :disabled="isSKUEdit"
              v-model="skuTableSelect.isBattery"
            >
              <a-radio :value="1"> 否 </a-radio>
              <a-radio :value="0"> 是 </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="标签类型：">
            <a-radio-group
              name="radioGroup"
              :default-value="1"
              :disabled="isSKUEdit"
              v-model="skuTableSelect.tagDefault"
            >
              <a-radio :value="1" :disabled="isSKUEdit"> 系统默认 </a-radio>
              <a-radio :value="2" :disabled="isSKUEdit"> 自定义标签 </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item
            v-if="skuTableSelect.tagDefault == '2'"
            label="自定义标签"
            prop="productTag"
          >
            <a-input
              :maxLength="100"
              :disabled="isSKUEdit"
              size="small"
              placeholder="请输入自定义标签"
              v-model="skuTableSelect.productTag"
            />
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="scI-info">
        <h3>海关信息</h3>
        <a-form-model
          :rules="secRules"
          ref="secRuleForm"
          :model="skuTableSelect"
          class="product-input"
        >
          <a-form-model-item label="申报价值：" prop="declaredValue">
            <a-input-number
              size="small"
              style="width: 60%"
              placeholder="申报价值（USD 美元）"
              v-model="skuTableSelect.declaredValue"
            />
          </a-form-model-item>
          <a-form-model-item label="海关编码：" prop="customsCode">
            <a-input
              :maxLength="100"
              size="small"
              placeholder="海关编码"
              v-model="skuTableSelect.customsCode"
            />
          </a-form-model-item>
        </a-form-model>
      </div>

      <div class="product-img">
        <h3>产品图片</h3>
        <div class="img-item">
          <div class="item-box">
            <div><span>正面:</span><span>(最多上传三张)</span></div>
            <a-upload
              :action="baseUrl + '/by-file/uploadFile'"
              :headers="headersRow"
              list-type="picture-card"
              :file-list="frontFileList"
              @preview="handlePreview"
              :before-upload="beforeUpload"
              @change="frontImgChange"
            >
              <div v-if="frontFileList.length < 3">
                <a-icon type="plus" />
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          </div>
          <div class="item-box">
            <div><span>反面:</span><span>(最多上传三张)</span></div>
            <a-upload
              :action="baseUrl + '/by-file/uploadFile'"
              :headers="headersRow"
              list-type="picture-card"
              :file-list="reverseFileList"
              @preview="handlePreview"
              @change="reverseImgChange"
              :before-upload="beforeUpload"
            >
              <div v-if="reverseFileList.length < 3">
                <a-icon type="plus" />
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          </div>
          <div class="item-box">
            <div><span>外包装:</span><span>(最多上传三张)</span></div>
            <a-upload
              :action="baseUrl + '/by-file/uploadFile'"
              :headers="headersRow"
              list-type="picture-card"
              :file-list="outerFileList"
              @preview="handlePreview"
              @change="outerImgChange"
              :before-upload="beforeUpload"
            >
              <div v-if="outerFileList.length < 3">
                <a-icon type="plus" />
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          </div>
          <a-modal
            :visible="previewVisible"
            :footer="null"
            @cancel="handleCancel"
          >
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </div>
      <div class="remark">
        <h3>备注</h3>
        <div style="margin-left: 2%">
          <span>
            备注：
            <a-textarea
              :maxLength="256"
              :rows="2"
              v-model="skuTableSelect.remarks"
            />
          </span>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import {
  SKU_tgasType,
  SKU_add,
  SKU_update,
  SKU_IsSku,
  SKU_useSku,
  // SKU_changeUnit,
} from "@/apis/clientSide/SKUManage/SKUList";
import { removefile } from "@/apis/common";
import baseUrl from "@/utils/baseUrl";
export default {
  props: ["platformOptions", "freedomOptions", "getTableData"],
  created() {
    this.getSKUtagsType();
  },
  mounted() {
    this.addSKUinfo();
    this.eidtRow();
  },
  data() {
    const checkCustomsCode = (rule, value, callback) => {
      if (!value) callback();
      if (value.length < 6) {
        callback(new Error("海关编码最小长度为6位字符"));
      } else if (value.length > 12) {
        callback(new Error("海关编码最大长度为12位字符"));
      } else {
        callback();
      }
    };
    const checkDeclaredValue = (rule, value, callback) => {
      const num = /^\d+$|^\d*\.\d+$/g;
      if (!value) {
        callback(new Error("申报价值需填写！"));
      } else if (!num.test(value)) {
        callback(new Error("申报价值只能为数字"));
      } else {
        callback();
      }
    };
    const checklwh = (rule, value, callback) => {
      if (
        (this.skuTableSelect.long || this.skuTableSelect.long == 0) &&
        (this.skuTableSelect.long || this.skuTableSelect.long == 0) &&
        (this.skuTableSelect.height || this.skuTableSelect.height == 0)
      ) {
        if (
          this.skuTableSelect.long * 1 > 274 ||
          this.skuTableSelect.width * 1 > 274 ||
          this.skuTableSelect.height * 1 > 274
        ) {
          this.status = "error";
          callback(new Error("长*宽*高最大值为274！"));
        } else {
          this.status = "success";
          callback();
        }
      } else {
        this.status = "error";
        callback(new Error("请填写长*宽*高！"));
      }
    };
    //验证是否含有中文
    const checkChineseName = (rule, value, callback) => {
      if (/.*[\u4e00-\u9fa5]+.*$/.test(value)) {
        callback();
      } else {
        callback(new Error("商品中文名必须包含汉字！"));
      }
    };
    //验证英文名
    const checkEnglishName = (rule, value, callback) => {
      if (/.*[\u4e00-\u9fa5]+.*$/.test(value)) {
        callback(new Error("仅支持包含字母,数字,-,_,&,点号.及空格！"));
      }
      if (value.length < 5) {
        callback(new Error("英文名最小长度为五个字符"));
      } else {
        callback();
      }
    };
    // sku验证
    const checksku = async (rule, value, callback) => {
      //如果没做更改的话就不用验证了
      if (value == this.oldSku) {
        callback();
      } else if (!this.skuTableSelect.sku) {
        callback(new Error("SKU需必填！"));
      }
      if (/.*[\u4e00-\u9fa5]+.*$/.test(value)) {
        callback(new Error("SKU不能含有中文"));
      }
      if (value.length < 5) {
        callback(new Error("SKU最小长度为四个字符"));
      }
      if (this.editFalge === true) {
        let { code } = await SKU_useSku(this.skuTableSelect.sku);
        if (code === "200") {
          let res = await SKU_IsSku(this.skuTableSelect.sku);
          if (res.code === "200") {
            this.SKUflag = true;
            callback();
          } else {
            callback(new Error("SKU已被使用，请重新输入！"));
          }
        }
      }
      if (this.editFalge === false) {
        let { code } = await SKU_IsSku(this.skuTableSelect.sku);
        if (code === "200") {
          this.SKUflag = true;
          callback();
        } else {
          callback(new Error("SKU已被使用，请重新输入！"));
        }
      }
    };
    return {
      chanUnit: {
        long: 0,
        width: 0,
        height: 0,
        longUnit: null,
        weight: "22",
        weightUnit: "lb",
      },
      loading: false,
      frontFileList: [],
      reverseFileList: [],
      outerFileList: [],
      unitOption: [
        { value: "0", label: "cm" },
        { value: "1", label: "in" },
      ],
      weightOption: [
        { value: "0", label: "g" },
        { value: "1", label: "lb" },
      ],
      previewVisible: false,
      previewImage: "",
      oldSku: "",
      status: "success",
      basicRules: {
        chineseName: [
          {
            required: true,
            message: "商品中文名称需填写！",
            trigger: "blur",
          },
          { validator: checkChineseName, trigger: "blur" },
        ],
        englishName: [
          {
            required: true,
            message: "商品英文名称需填写！",
            trigger: "blur",
          },
          { validator: checkEnglishName, trigger: "blur" },
        ],
        sku: [
          {
            required: true,
            trigger: "blur",
            message: "sku需填写！",
            resetFields: true,
          },
          { validator: checksku, trigger: "blur" },
        ],
        width: [
          {
            validator: checklwh,
            trigger: "blur",
            resetFields: true,
          },
        ],
        weight: [
          {
            required: true,
            trigger: "blur",
            message: "商品重量需填写！",
          },
        ],
        platformClassify: [
          {
            required: true,
            message: "平台分类需选择！",
            trigger: "change",
          },
        ],
        packingTypeName: [
          {
            required: true,
            message: "包装类型需选择！",
            trigger: "change",
          },
        ],
        productTag: [
          {
            required: true,
            message: "自定义标签需填写！",
            trigger: "blur",
          },
        ],
      },
      secRules: {
        declaredValue: [
          {
            validator: checkDeclaredValue,
            trigger: "blur",
            required: true,
            resetFields: true,
          },
        ],
        customsCode: [
          {
            validator: checkCustomsCode,
            required: false,
            trigger: "blur",
          },
        ],
      },
      SKUTitle: "新建SKU",
      isSKUEdit: false,
      SKUflag: false,
      // 上传标杆
      uploadImgFlag: false,
      uploadFlag: false,
      headersRow: {
        authorization: "authorization-text",
        token: sessionStorage.getItem("tk"),
      },
      baseUrl,
      // 是否修改标杆
      editFalge: false,
      visible: false,
      //上传图标信息
      fileList: [],
      //标签类型
      tagsType: [],
      //   编辑标杆
      skuIsNo: true,
      addFlage: true,
      //图片数组
      productPictureArray: [],
      //需要表单数据
      skuTableSelect: {
        //包装名字
        packingTypeName: "",
        // 中文名称
        chineseName: "",
        // 当前页,默认 1
        current: 0,
        // 海关编码
        customsCode: "",
        // 申报价值
        declaredValue: "",
        //  英文名称
        englishName: "",

        // 是否包含电池
        isBattery: 1,
        // 是否删除
        isDelete: 0,
        // 是否液体 是否液体
        isLiquid: 1,
        // 是否归档 是否归档
        isOnFile: 0,

        // 包装类型（字典表数据） 包装类型
        packingType: "",
        // 平台产品分类
        platformClassify: [],
        // 产品品牌
        productBrand: "",
        // 产品图片
        productPicture: [],
        // 产品标签系统默认生成（暂定8位）
        productTag: "",
        // 产品型号
        productType: "",
        // 生产地址
        productionAddress: "",
        //  关联sku
        relevancySku: "",
        //  备注信息
        remarks: "",
        // // 自有分类 用户建立的分类
        // selfClassify: [],
        // 每页显示条数
        size: 0,
        //  sku
        sku: "",
        // 标签默认类型
        tagDefault: 1,
        // 长
        long: null,
        // 宽
        width: null,
        // 高
        height: null,
        // 重量
        weight: null,
        //长宽高得单位
        unitSystem: "0",
        //重量单位
        unitWeight: "0",
      },
    };
  },
  methods: {
    // //封装一个改变单位换算得方法
    // async changeNUMber(old, go, oldObj) {
    //   let res = await SKU_changeUnit({
    //     long: this.skuTableSelect.long,
    //     width: this.skuTableSelect.width,
    //     height: this.skuTableSelect.height,
    //     weight: this.skuTableSelect.weight,
    //     nowUnitSystem: old,
    //     nowUnitWeight: old,
    //     unitSystem: go,
    //     unitWeight: go,
    //   });
    //   if (res.code == "200") {
    //     this.skuTableSelect.long = res.responseBody.long;
    //     this.skuTableSelect.width = res.responseBody.width;
    //     this.skuTableSelect.height = res.responseBody.height;
    //     this.skuTableSelect.weight = res.responseBody.weight;
    //     this.chanUnit.long = Number(oldObj.long).toFixed(2);
    //     this.chanUnit.width = Number(oldObj.width).toFixed(2);
    //     this.chanUnit.height = Number(oldObj.height).toFixed(2);
    //     this.chanUnit.weight = Number(oldObj.weight).toFixed(2);
    //   }
    // },
    // //改变重量单位
    // changeWeightUnit(value) {
    //   this.$refs.infoRuleForm.validateField("width", (widthError) => {
    //     if (widthError === "") {
    //       if (!this.skuTableSelect.weight) {
    //         if (value == "0") {
    //           this.skuTableSelect.weightUnit = "1";
    //           this.skuTableSelect.unitSystem = "1";
    //         } else {
    //           this.skuTableSelect.unitSystem = "0";
    //           this.skuTableSelect.weightUnit = "0";
    //         }
    //         this.$message.error("请先填写重量！");
    //         return false;
    //       }
    //       let oldObj = JSON.parse(JSON.stringify(this.skuTableSelect));
    //       if (value == 0) {
    //         this.skuTableSelect.unitWeight = "0";
    //         this.chanUnit.weightUnit = "lb";
    //         this.chanUnit.longUnit = "in";
    //         this.changeNUMber(1, 0, oldObj);
    //       } else if (value == 1) {
    //         this.skuTableSelect.unitWeight = "1";
    //         this.chanUnit.weightUnit = "g";
    //         this.chanUnit.longUnit = "cm";
    //         this.changeNUMber(0, 1, oldObj);
    //       }
    //     } else {
    //       this.$message.error("请先填写长宽高！");
    //       if (value == "0") {
    //         this.skuTableSelect.unitWeight = "1";
    //         this.skuTableSelect.unitSystem = "1";
    //       } else {
    //         this.skuTableSelect.unitSystem = "0";
    //         this.skuTableSelect.unitWeight = "0";
    //       }
    //     }
    //   });
    // },
    // //改变单位
    // changeUnit(value) {
    //   this.$refs.infoRuleForm.validateField("width", (widthError) => {
    //     if (widthError === "") {
    //       if (!this.skuTableSelect.weight) {
    //         if (value == "0") {
    //           this.skuTableSelect.unitWeight = "1";
    //           this.skuTableSelect.unitSystem = "1";
    //         } else {
    //           this.skuTableSelect.unitSystem = "0";
    //           this.skuTableSelect.unitWeight = "0";
    //         }
    //         this.$message.error("请先填写重量！");
    //         return false;
    //       }
    //       let oldObj = JSON.parse(JSON.stringify(this.skuTableSelect));
    //       if (value == 0) {
    //         this.skuTableSelect.unitWeight = "0";
    //         this.chanUnit.weightUnit = "lb";
    //         this.chanUnit.longUnit = "in";
    //         this.changeNUMber(1, 0, oldObj);
    //       } else if (value == 1) {
    //         this.skuTableSelect.unitWeight = "1";
    //         this.chanUnit.weightUnit = "g";
    //         this.chanUnit.longUnit = "cm";
    //         this.changeNUMber(0, 1, oldObj);
    //       }
    //     } else {
    //       this.$message.error("请先填写长宽高！");
    //       if (value == "0") {
    //         this.skuTableSelect.unitWeight = "1";
    //         this.skuTableSelect.unitSystem = "1";
    //       } else {
    //         this.skuTableSelect.unitSystem = "0";
    //         this.skuTableSelect.unitWeight = "0";
    //       }
    //     }
    //   });
    // },
    //关闭或取消按钮
    handleClose() {
      this.visible = false;
      this.frontFileList = [];
      this.reverseFileList = [];
      this.outerFileList = [];
      this.skuTableSelect = {
        //包装名字
        packingTypeName: "",
        // 中文名称
        chineseName: "",
        // 当前页,默认 1
        current: 0,
        // 海关编码
        customsCode: "",
        // 申报价值
        declaredValue: "",
        //  英文名称
        englishName: "",
        // 是否包含电池
        isBattery: 1,
        // 是否删除
        isDelete: 0,
        // 是否液体 是否液体
        isLiquid: 1,
        // 是否归档 是否归档
        isOnFile: 0,
        // 包装类型（字典表数据） 包装类型
        packingType: "",
        // 平台产品分类
        platformClassify: [],
        // 产品品牌
        productBrand: "",
        // 产品图片
        productPicture: [],
        // 产品标签系统默认生成（暂定8位）
        productTag: "",
        // 产品型号
        productType: "",
        // 生产地址
        productionAddress: "",
        //  关联sku
        relevancySku: "",
        //  备注信息
        remarks: "",
        // 自有分类 用户建立的分类
        // selfClassify: [],
        // 每页显示条数
        size: 0,
        //  sku
        sku: "",
        // 标签默认类型
        tagDefault: 1,
        // 长
        long: null,
        // 宽
        width: null,
        // 高
        height: null,
        // 重量
        weight: null,
        //长宽高得单位
        unitSystem: "0",
        //重量单位
        unitWeight: "0",
      };
      this.loading = false;
      this.$refs.infoRuleForm.resetFields();
      this.$refs.secRuleForm.resetFields();
    },
    async handlePreview(file) {
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    //输入重量时候得事件
    changeweight() {
      if (this.skuTableSelect.weight * 1 < 454) {
        this.chanUnit.weightUnit = "oz";
        this.chanUnit.weight = (
          this.skuTableSelect.weight *
          1 *
          0.0352739619496
        ).toFixed(2);
      } else {
        this.chanUnit.weightUnit = "lb";
        this.chanUnit.weight = (
          this.skuTableSelect.weight *
          1 *
          0.00220462262185
        ).toFixed(2);
      }
    },
    changeLong(num) {
      // if (this.skuTableSelect.unitSystem == "0") {
      this.chanUnit.longUnit = "in";
      if (num == 1) {
        this.chanUnit.long = (
          this.skuTableSelect.long *
          1 *
          0.393700787402
        ).toFixed(2);
      } else if (num == 2) {
        this.chanUnit.width = (
          this.skuTableSelect.width *
          1 *
          0.393700787402
        ).toFixed(2);
      } else if (num == 3) {
        this.chanUnit.height = (
          this.skuTableSelect.height *
          1 *
          0.393700787402
        ).toFixed(2);
      }
      // // }
      // if (this.skuTableSelect.unitSystem == "1") {
      //   this.chanUnit.longUnit = "cm";
      //   if (num == 1) {
      //     this.chanUnit.long = (
      //       (this.skuTableSelect.long * 1) /
      //       0.393700787402
      //     ).toFixed(2);
      //   } else if (num == 2) {
      //     this.chanUnit.width = (
      //       (this.skuTableSelect.width * 1) /
      //       0.393700787402
      //     ).toFixed(2);
      //   } else if (num == 3) {
      //     this.chanUnit.height = (
      //       (this.skuTableSelect.height * 1) /
      //       0.393700787402
      //     ).toFixed(2);
      //   }
      // }
    },
    //手动验证长宽高
    changeLwh() {
      this.$refs.infoRuleForm.validateField("width", (widthError) => {
        console.log(widthError);
      });
    },

    goTo(file) {
      window.open(file);
    },
    //包装改变
    changePackingType(value) {
      this.tagsType.forEach((item) => {
        if (value === item.key) {
          this.skuTableSelect.packingTypeName = item.title;
        }
      });
    },
    //提交模态框
    async handleOk() {
      this.loading = true;
      this.skuTableSelect.productPicture = [];
      this.frontFileList.forEach((item) => {
        item.imgType = "1";
      });
      this.reverseFileList.forEach((item) => {
        item.imgType = "2";
      });
      this.outerFileList.forEach((item) => {
        item.imgType = "3";
      });
      let fileArr = this.frontFileList.concat(
        this.reverseFileList.concat(this.outerFileList)
      );
      fileArr.forEach((item) => {
        let obj = {
          uid: item.uid,
          url: item.url,
          name: item.name,
          imgType: item.imgType,
        };
        this.skuTableSelect.productPicture.push(obj);
      });
      this.skuTableSelect.productPicture = JSON.stringify(
        this.skuTableSelect.productPicture
      );
      this.$refs.infoRuleForm.validate(async (valid1) => {
        this.$refs.secRuleForm.validate(async (valid) => {
          if (!valid1 || !valid) {
            this.loading = false;
            return false;
          } else {
            //映射一个发送后台的对象
            let skuObj = JSON.parse(JSON.stringify(this.skuTableSelect));
            // 转换数组为字符串
            for (let key in skuObj) {
              if (Array.isArray(skuObj[key])) {
                skuObj[key] = skuObj[key].join(",");
              }
            }
            // 如果是新增界面
            if (this.addFlage) {
              let { code } = await SKU_add(skuObj);
              if (code === "10000") {
                this.getTableData();
                this.SKUflag = false;
                this.handleClose();
              }
              //或者是修改界面
            } else {
              // 转换数组为字符串
              for (let key in skuObj) {
                if (Array.isArray(skuObj[key])) {
                  skuObj[key] = skuObj[key].join(",");
                }
              }
              let res = await SKU_update(skuObj);
              if (res.code === "10000") {
                this.getTableData();
                this.SKUflag = false;
                this.handleClose();
              } else if (res.code == "10003") {
                this.$message.error("请修改数据后再保存！");
                return false;
              } else {
                this.SKUflag = false;
                this.handleClose();
                return false;
              }
            }
          }
        });
      });
    },
    //平台产品选项框
    onChangeplatformOptions(value) {
      this.skuTableSelect.platformClassify = value;
    },
    // //自有产品选项框
    // onChangefreedomOptions(value) {
    //   this.skuTableSelect.selfClassify = value;
    // },
    //正面图片上传
    async frontImgChange(info) {
      if (this.uploadImgFlag) {
        return false;
      }
      if (info.fileList) {
        this.frontFileList = info.fileList;
      } else {
        return false;
      }
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} 上传成功`);
        this.frontFileList.forEach((item) => {
          if (item.response) {
            item.url = item.response.responseBody[0];
          }
        });
      } else if (info.file.status === "removed") {
        let res = await removefile([info.file.url]);
        res;
      }
    },
    //反面图片上传
    async reverseImgChange(info) {
      if (this.uploadImgFlag) {
        return false;
      }
      if (info.fileList) {
        this.reverseFileList = info.fileList;
      } else {
        return false;
      }
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} 上传成功`);
        this.reverseFileList.forEach((item) => {
          if (item.response) {
            item.url = item.response.responseBody[0];
          }
        });
      } else if (info.file.status === "removed") {
        let res = await removefile([info.file.url]);
        res;
      }
    },
    //外包装图片上传
    async outerImgChange(info) {
      if (this.uploadImgFlag) {
        return false;
      }
      if (info.fileList) {
        this.outerFileList = info.fileList;
      } else {
        return false;
      }
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} 上传成功`);
        this.outerFileList.forEach((item) => {
          if (item.response) {
            item.url = item.response.responseBody[0];
          }
        });
      } else if (info.file.status === "removed") {
        let res = await removefile([info.file.url]);
        res;
      }
    },
    //限制上传图片大小
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      if (!isJpgOrPng) {
        this.$message.error("你只能上传JPG/PNG/jpeg!");
        this.uploadImgFlag = true;
      }
      const isLt2M = file.size < 1048576;
      if (!isLt2M) {
        this.$message.error("只能上传1MB下的文件!");
        this.uploadImgFlag = true;
      }
      if (isLt2M && isJpgOrPng) {
        this.uploadImgFlag = false;
      }
      return isJpgOrPng && isLt2M;
    },
    //新建SKU
    addSKUinfo() {
      this.$bus.$off("showModel");
      this.$bus.$on("showModel", () => {
        this.skuTableSelect.isBattery = 1;
        this.skuTableSelect.isLiquid = 1;
        this.skuTableSelect.tagDefault = 1;
        this.skuTableSelect.platformClassify = [];
        this.skuTableSelect.packingType = undefined;
        this.skuTableSelect.productPicture = [];
        this.frontFileList = [];
        this.reverseFileList = [];
        this.outerFileList = [];
        this.addFlage = true;
        this.SKUTitle = "新建SKU";
        this.isSKUEdit = false;
        this.visible = true;
      });
    },
    //编辑弹出框赋值
    eidtRow() {
      this.$bus.$off("skuListRowData");
      this.$bus.$on("skuListRowData", async (data, flag) => {
        //保存当前的sku，验证会用到
        this.oldSku = data.sku;
        if (flag === "edit") {
          this.SKUTitle = "编辑SKU";
          this.addFlage = false;
          this.editFalge = true;
        } else if (flag === "info") {
          this.editFalge = false;
          this.addFlage = false;
          this.SKUTitle = "查看SKU";
        }
        this.skuTableSelect = JSON.parse(JSON.stringify(data));
        this.addFlage = false;
        this.visible = true;
        this.skuTableSelect.platformClassify = Array.isArray(
          data.platformClassify
        )
          ? this.skuTableSelect.platformClassify
          : data.platformClassify === null
          ? []
          : this.skuTableSelect.platformClassify.split(",");
        this.skuTableSelect.isBattery = data.isBattery * 1;
        this.skuTableSelect.isLiquid = data.isLiquid * 1;
        this.skuTableSelect.tagDefault = data.tagDefault * 1;
        this.tagsType.forEach((item) => {
          if (data.packingType === item.key) {
            this.skuTableSelect.packingTypeName = item.title;
          }
        });
        // this.skuTableSelect.selfClassify = Array.isArray(data.selfClassify)
        //   ? this.skuTableSelect.selfClassify
        //   : data.selfClassify === null
        //   ? []
        //   : this.skuTableSelect.selfClassify.split(",");
        if (this.skuTableSelect.productPicture) {
          let imgArr = JSON.parse(this.skuTableSelect.productPicture);
          this.frontFileList = imgArr.filter((item) => {
            return item.imgType == "1";
          });
          this.reverseFileList = imgArr.filter((item) => {
            return item.imgType == "2";
          });
          this.outerFileList = imgArr.filter((item) => {
            return item.imgType == "3";
          });
        }
        //单位复现
        this.chanUnit.longUnit = "in";
        this.chanUnit.long = (
          this.skuTableSelect.long *
          1 *
          0.393700787402
        ).toFixed(2);

        this.chanUnit.width = (
          this.skuTableSelect.width *
          1 *
          0.393700787402
        ).toFixed(2);

        this.chanUnit.height = (
          this.skuTableSelect.height *
          1 *
          0.393700787402
        ).toFixed(2);

        if (this.skuTableSelect.weight * 1 < 454) {
          this.chanUnit.weightUnit = "oz";
          this.chanUnit.weight = (
            this.skuTableSelect.weight *
            1 *
            0.0352739619496
          ).toFixed(2);
        } else {
          this.chanUnit.weightUnit = "lb";
          this.chanUnit.weight = (
            this.skuTableSelect.weight *
            1 *
            0.00220462262185
          ).toFixed(2);
        }
        this.uploadFlag = true;
        let { code } = await SKU_useSku(this.skuTableSelect.sku);
        if (code != "200") {
          this.isSKUEdit = true;
        } else {
          this.$message.warning(
            "SKU一旦装箱就无法修改必填项信息，请认真核实信息！"
          );
          this.isSKUEdit = false;
        }
      });
    },
    //获取标签类型
    async getSKUtagsType() {
      let { code, responseBody } = await SKU_tgasType({
        tagType: 3,
      });
      if (code === "200") {
        this.tagsType = responseBody;
      }
    },
    filter(inputValue, path) {
      return path.some(
        (option) =>
          option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
      );
    },
  },
};
</script>
<style lang="less" scoped>
.product-info {
  /deep/.product-input {
    width: 90%;
    padding: 0 20px;
    display: flex;
    flex-wrap: wrap;
    .ant-form-item-with-help {
      margin-bottom: 24px !important;
    }
    .ant-form-item {
      width: 50%;
      display: flex;
      height: 30px;

      .ant-form-item-label {
        width: 120px;
      }
      .ant-form-item-control-wrapper {
        width: 100%;
        .ant-input {
          width: 70%;
        }
      }
    }
    .my-class {
      .ant-form-item-control-wrapper {
        width: 100%;
        .ant-input {
          width: 100%;
        }
      }
    }
    .plat-class {
      .ant-form-item-control-wrapper {
        width: 100%;
        .ant-input {
          width: 100%;
        }
      }
    }
    .lwh {
      display: flex;
      width: 100% !important;
      .ant-form-item-label {
        width: 160px !important;
      }
      .ant-form-item-children {
        display: flex;
        align-items: center;
        .ant-form-item {
          width: 20%;
        }
        .ant-form-item:last-child {
          flex: 1;
        }
      }
      .height {
        .ant-form-item-children {
          height: 40px;
        }
      }
    }
    .nuclear {
      .ant-form-item-label {
        width: 140px;
      }
    }
  }
}
.scI-info {
  /deep/.product-input {
    padding: 0 20px;
    display: flex;
    flex-wrap: wrap;
    .ant-form-item-with-help {
      margin-bottom: 24px !important;
    }
    .ant-form-item {
      width: 50%;
      display: flex;
      height: 30px;

      .ant-form-item-label {
        width: 120px;
      }
      .ant-form-item-control-wrapper {
        width: 100%;
        .ant-input {
          width: 60%;
        }
      }
    }
  }
}
.product-img {
  .img-item {
    .item-box {
      display: flex;
      align-items: center;
      > div {
        width: 15%;
        text-align: center;
        display: flex;
        flex-direction: column;
      }
    }
  }
  // .imgurl {
  //   position: relative;
  // }
  // .close {
  //   position: absolute;
  //   top: -23px;
  //   left: 55px;
  //   color: #fff;
  //   font-size: 18px;
  //   z-index: 999;
  //   cursor: pointer;
  // }
  // width: 90%;
  // margin-bottom: 20px;
  // /* tile uploaded pictures */
  // /deep/.ant-upload-list-item {
  //   float: left;
  //   width: 150px;
  //   margin-right: 8px;
  // }
}
</style>
